package cn.ilikes.tools.nosql.jpa.springs;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;

import cn.ilikes.tools.nosql.jpa.persistences.ABJPASQLEntityManager;

public abstract class BaseService extends BaseQuery implements IBaseService {

	@Override
	public <V> V findEntity(Serializable key, Class<V> clazz) throws SpringErrorException {
		EntityManager entityManager = this.getEntityManager();
		return entityManager.find(clazz, key);
	}

	@Override
	public <V> V get(Serializable key, Class<V> clazz) throws SpringErrorException {

		EntityManager entityManager = this.getEntityManager();

		return entityManager.find(clazz, key);
	}

	@Override
	public <V> V load(Serializable key, Class<V> clazz) throws SpringErrorException {
		EntityManager entityManager = this.getEntityManager();
		return entityManager.getReference(clazz, key);
	}

	@Override
	public <E> E merge(E entity) throws SpringErrorException {

		EntityManager entityManager = this.getEntityManager();
		return entityManager.merge(entity);
	}

	@Override
	public <T> T remove(Serializable key, Class<T> clazz) throws SpringErrorException {

		EntityManager entityManager = this.getEntityManager();
		T entity = load(key, clazz);
		if (entity == null)
			throw new SpringErrorException(" remove entity no  success ! not find key : " + key + " entity !  ");
		entityManager.remove(entity);
		return entity;
	}

	@Override
	public <V> V remove(V entity) throws SpringErrorException {
		EntityManager entityManager = this.getEntityManager();
		entityManager.remove(entity);
		return entity;
	}

	@Override
	public <V> void save(V entity) throws SpringErrorException {
		if (entity == null)
			throw new SpringErrorException(" save  entity no  success ! save's entity is  null !  ");
		EntityManager entityManager = this.getEntityManager();
		entityManager.persist(entity);

	}

	@Override
	public <V> void update(V entity) throws SpringErrorException {
		if (entity == null)
			throw new SpringErrorException(" update  entity no  success ! update's entity is  null !  ");
		EntityManager entityManager = this.getEntityManager();
		entityManager.merge(entity);

	}

}
